package au.edu.unsw.editingtool.db;

import java.sql.SQLException;
import java.util.Hashtable;

import au.edu.unsw.editingtool.global.EditingToolException;
import au.edu.unsw.editingtool.global.EditingToolGlobalConstant;

public class DBLogin extends DBManager {
	
	protected void setupDBMapping() {
		if (MappingTable.size() > 0)
			return;
		MappingTable.put("Username", "username");
		MappingTable.put("Password", "password");
		MappingTable.put("Affiliation", "affiliation");
		MappingTable.put("Group", "group");
		MappingTable.put("Status", "status");
		MappingTable.put("Note", "note");
	}
	
	public DBLogin() {
		this.table = "login";
		this.primaryKeys = new String[]{"Username"};
		this.setupDBMapping();
	}
	
	public void addAuthor(Hashtable<String, String> userInfo) throws EditingToolException, ClassNotFoundException, SQLException {
		this.setTable(this.table, "");
		userInfo.put("Group", EditingToolGlobalConstant.authorGroupID);
		userInfo.put("Status", EditingToolGlobalConstant.userStatusActive);
		this.setColumnValues(userInfo);
		
		this.initDB();
		this.insert(false, true);		
		this.clean();
	}
	
	public void addReviewer(Hashtable<String, String> userInfo) throws EditingToolException, ClassNotFoundException, SQLException {
		this.setTable(this.table, "");
		userInfo.put("Group", EditingToolGlobalConstant.reviewerGroupID);
		userInfo.put("Status", EditingToolGlobalConstant.userStatusActive);
		this.setColumnValues(userInfo);
		
		this.initDB();
		this.insert(false, true);
		this.clean();
	}
	
	
/*	
	public void updateUserInfo(Hashtable<String, String> userinfo) throws EditingToolException, SQLException {
		this.setTable(this.table, "");
		
		this.setFieldsCondition("Username", setEqual(userinfo.get("Username")));
		userinfo.remove("Username");
		this.setColumnValues(userinfo);
		this.updateRecords();
		this.clean();
	}
*/
	
	public boolean userExists(String username) throws ClassNotFoundException, SQLException, EditingToolException {
		String fields[] = {"Username"};
		this.setTable(this.table, "");
		this.setFieldsCondition("Username", this.setEqual(username));
		this.addField(fields);
		
		this.initDB();
		this.selectRecords();
		if (this.ResultSet == null) {
			this.clean();
			return false;
		}
		boolean result = this.ResultSet.next();
		this.clean();
		return result;
	}
	
}
